package ru.payment.wm.impl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

import ru.payment.wm.Signer;
import ru.payment.wm.WebMoneyException;
import wmsignerjx.Buffer;

/**
 * User: sergey
 * Date: 28.04.2009
 * Time: 12:35:05
 */
public class SignerImpl implements Signer {

  private String keyPath;
  private wmsignerjx.Signer signer;

  public SignerImpl() {
  }

  public String getKeyPath() {
    return keyPath;
  }

  public void setKeyPath(String keyPath) {
    this.keyPath = keyPath;
    try {
      loadKey(keyPath);
    } catch (WebMoneyException e) {
      throw new Error(e);
    }
  }

  private void loadKey(String classicKeyPath) throws WebMoneyException {

    try {

      BufferedReader fr = new BufferedReader(new FileReader(classicKeyPath));

      String sz = fr.readLine();

      String[] aKeys = sz.split(":");

      byte[] bExponent = Base64.decodeBase64(aKeys[0]);
      byte[] bModulus = Base64.decodeBase64(aKeys[1]);
      // System.out.println("["+bExponent.length+"]"+Arrays.toString(bExponent)+" # ["+bModulus.length+"] "+Arrays.toString(bModulus));

      int[] nExponent = new int[(bExponent.length + 4 - 1) / 4];
      int[] nModulus = new int[(bModulus.length + 4 - 1) / 4];

      Buffer.BlockCopy(bExponent, 0, nExponent, 0, bExponent.length);
      Buffer.BlockCopy(bModulus, 0, nModulus, 0, bModulus.length);
      //System.out.println(Arrays.toString(nExponent)+" # "+Arrays.toString(nModulus));

      signer = new wmsignerjx.Signer(nExponent, nModulus);

    } catch (IOException e) {
      new AuthorizationException(e);
    }

  }

  public String sign(String srcString) throws WebMoneyException {
    return signer.Sign(srcString);
  }

}
